import api from '../../utils/api';
import util from '../../utils/index';

//获取应用实例
const app = getApp()
Page({
    data: {
        imageUploadHeader: {
            "Content-Type": "multipart/form-data",
        },
        imageUploadFormData: {},
        html: '',
        productId: '',
        productInfo: {},
        specArray:[],
        specIndex:0,
        specName:'',
        productArray: ['其它', '水果生鲜', '邻里闲置', '生活用品', '五湖四海'],
        productIndex: 0,
        isStartShow: false,
        startTime: '',
        isEndShow: false,
        endTime: '',

        title: '',
        subTitle: '',
        publisherPhone: '',
        shipAddress: '',
        price: '0.00',
        marketPrice: '0.00',
        place: '',
        loading: false,
        isDisabled: true,
        isParse: false
    },

    /**
     * 页面初始化是获取ID 根据有无产品id  saveOrUpdate
     * @param options
     */
    onLoad: function (options) {
        var that = this;
        that.setData({
            productId: options.id
        })

        if (options.id != null) {
            that.renderProduct(options.id);
        } else {
            that.setData({
                isParse: true
            })
        }

        this.loadSpecs();

        // 获取上传图片的token
        util.request({'url': api.uploadToken}).then(res=> {
            that.setData({
                "imageUploadFormData": {
                    "token": res.data.accessToken
                }
            })
        })


    },


    // 获取规格信息
    loadSpecs:function(){
        var that = this;
        util.request({'url': api.specItemUrl}).then(res=> {
            console.log(res);
            that.setData({
                    "specArray": res.data,
                    "specName": res.data[0].name
            })
        })
    },


    //回填信息
    renderProduct: function (id) {
        this.setData({
            isDisabled: false
        })

        util.request({
            url: util.templateFunc(api.productDetailUrl, {id: id})
        }).then(res => {
            if (res && res.data) {
                console.log(res.data)
                this.setData({
                    "publisherPhone": res.data.publisherPhone,
                    "title": res.data.title,
                    "shipAddress": res.data.shipAddress,
                    "html": res.data.description,
                    "subTitle": res.data.subtitle,
                    "productIndex": res.data.category,
                    "specIndex": res.data.specification,
                    "shipAddress": res.data.shipAddress,
                    "place":res.data.place,
                    "price":(res.data.price)/100,
                    "marketPrice":(res.data.marketPrice)/100
                });
            }
            this.setData({
                isDisabled: true,
                isParse: true
            })
        })
    },

    // 选择开始时间
    showStartSelect: function (e) {
        this.setData({
            isStartShow: true
        })
    },
    handleSelecteStartDate(e) {
        this.setData({
            startTime: e.detail.date,
            isStartShow: false
        })
    },

    // 结束时间
    showEndSelect: function (e) {
        this.setData({
            isEndShow: true
        })
    },
    handleSelecteEndDate(e) {
        this.setData({
            endTime: e.detail.date,
            isEndShow: false
        })
    },


    // 点击完成
    finish: function (e) {
        if (!e.detail.content) {
            wx.showModal({
                title: '发布失败',
                content: '产品描述不能为空',
                showCancel: false
            });
            return false;
        }

        //正则匹配img
        var str = e.detail.content;
        //匹配图片（g表示匹配所有结果i表示区分大小写）
        var imgReg = /<img.*?(?:>|\/>)/gi;
        //匹配src属性
        var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
        var arr = str.match(imgReg);
        if (arr === null || !arr.length) {
            wx.showModal({
                title: '发布失败',
                content: '产品描述至少拥有一张图片',
                showCancel: false
            });
            return false;
        }
        var imgUrl = arr[0].match(srcReg)[1];

        // 验证必填

        if (!this.data.title) {
            wx.showModal({
                title: '发布失败',
                content: '产品名称不能为空',
                showCancel: false
            });
            return false;
        }

        if (!this.data.shipAddress) {
            wx.showModal({
                title: '发布失败',
                content: '地址不能为空',
                showCancel: false
            });
            return false;
        }

        var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
        if (!myreg.test(this.data.publisherPhone)) {
            wx.showModal({
                title: '发布失败',
                content: '手机号格式不正确',
                showCancel: false
            });
            return false;
        }

        //
        // if (!this.data.startTime) {
        //     wx.showModal({
        //         title: '发布失败',
        //         content: '起始时间不能为空',
        //         showCancel: false
        //     });
        //     return false;
        // }
        //
        // if (!this.data.endTime) {
        //     wx.showModal({
        //         title: '发布失败',
        //         content: '结束时间不能为空',
        //         showCancel: false
        //     });
        //     return false;
        // }


        if (!this.data.publisherPhone) {
            wx.showModal({
                title: '发布失败',
                content: '联系方式不能为空',
                showCancel: false
            });
            return false;
        }


        this.setData({
            loading: true
        })

        let data = {
            "id": this.data.productId,
            "publisherPhone": this.data.publisherPhone,
            "title": this.data.title,
            "subtitle": this.data.subTitle,
            "category": this.data.productIndex,
            "specification" : this.data.specIndex,
            "shipAddress": this.data.shipAddress,
            "description": e.detail.content,
            "place":this.data.place,
            "price":(this.data.price)*100,
            "marketPrice":(this.data.marketPrice)*100,
            "imgUrl": imgUrl
        }


        console.log(data)



        const Method = (this.data.productId === undefined || this.data.productId === null || this.data.productId === '') ? 'POST' : 'PUT';
        util.request({
            'url': api.postProductsUrl,
            method: Method,
            header: {
                'content-type': 'application/json',
                'x-auth-token': wx.getStorageSync('sessionId')
            },
            data: data
        }).then(res=> {
            if (res && res.errorCode === 0) {
                wx.showToast({
                    title: '发布成功!',
                    icon: 'success',
                    duration: 1000
                })

                setTimeout(function () {
                    wx.switchTab({
                        url: "/pages/index/index",
                        // 跳转后刷新界面
                        success: function (e) {
                            var page = getCurrentPages().pop();
                            if (page == undefined || page == null) return;
                            page.onLoad();
                        }
                    });
                }, 1000)
            } else {
                wx.showToast({
                    title: '服务器异常',
                    icon: 'fail',
                    duration: 1000
                })

                this.setData({
                    loading: false
                })
            }

        })
    },


    bindPickerChange: function (e) {
        this.setData({
            productIndex: e.detail.value
        })
    },

    bindSpecPickerChange:function (e) {
        this.setData({
            specIndex: e.detail.value,
            specName: this.data.specArray[e.detail.value].name
        })
    },


    // 获取输入框数据
    titleInput: function (e) {
        this.setData({
            title: e.detail.value
        })
    },
    publisherPhoneInput: function (e) {
        this.setData({
            publisherPhone: e.detail.value
        })
    },
    shipAddressInput: function (e) {
        this.setData({
            shipAddress: e.detail.value
        })
    },
    subTitleInput: function (e) {
        this.setData({
            subTitle: e.detail.value
        })
    },
    priceInput: function (e) {
        this.setData({
            price: e.detail.value
        })
    },
    marketPriceInput: function (e) {
        this.setData({
            marketPrice: e.detail.value
        })
    },
    placeInput: function (e) {
        this.setData({
            place: e.detail.value
        })
    }


})